package com.borun.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.borun.dao.UserRepository;
import com.borun.entity.UserBean;
import com.borun.entity.condition.UserCondition;
import com.borun.service.UserService;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
    private UserRepository userRepository;
	
	@Override
	public UserBean findByUsername(String username) {
    	return userRepository.findDistinctByUsername(username);
	}

	@Override
	public UserBean login(UserBean userbean) {
		return userRepository.findByUsernameAndPassword(userbean.getUsername(), userbean.getPassword());
	}

	@Override
	public UserBean saveOrupdate(UserBean userBean) {
		return userRepository.saveAndFlush(userBean);
	}

	@Override
	public void delete(Integer id) {
		if(id != null && id > 0)
			userRepository.delete(id);
	}

	@Override
	public void delete(List<Integer> ids) {
		if(ids != null && ids.size() > 0)
			for (Integer id:ids)
				delete(id);
	}

	@Override
	public Page<UserBean> getAll(int pageIndex, int pageSize) {
        return userRepository.findAll(new PageRequest(pageIndex - 1, pageSize));
	}

	@Override
	public Page<UserBean> getByCondition(UserCondition userCondition) {		
		return userRepository.findByCondition(userCondition.getUsername(),new PageRequest(userCondition.getPageIndex(), userCondition.getPageSize()));
	}

	@Override
	public UserBean getDetail(Integer id) {
		return userRepository.findOne(id);
	}


	@Override
	public UserBean regist(UserBean userBean){
		UserBean loginUser = login(userBean);
		if(loginUser != null)
			return userRepository.saveAndFlush(userBean);
		else
			return null;
	}
	


}
